<template>
  <div class="category-view">
    <el-card>
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="beforeClose"
      >
        <category-edit v-bind.sync="editCate" @submit="onSubmit" />
      </el-dialog>
      <div style="display: flex; justify-content: space-between">
        <el-button
          type="primary"
          @click="
            dialogVisible = true;
            isEdit = false;
          "
          >新建商品分类</el-button
        >
      </div>

      <el-table
        :data="treeCategory"
        row-key="id"
        lazy
        :load="load"
        :tree-props="{ hasChildren: 'has_children' }"
        style="margin-top: 10px"
        ref="table"
      >
        <el-table-column prop="id" label="编号"></el-table-column>
        <el-table-column prop="name" label="类别名称"></el-table-column>
        <el-table-column prop="sort_order" label="显示顺序"></el-table-column>
        <el-table-column prop="banner_image_alt" label="展示图片">
          <template v-slot="{ row }">
            <el-image
              style="width: 50px; height: 50px line-height:50px; text-align:center"
              :src="row.banner_image_alt"
              fit="scale-down"
            >
              <template v-slot:error class="image-slot">
                <i
                  class="el-icon-picture-outline"
                  style="font-size: 40px; color: #ccc"
                ></i> </template
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="层级">
          <template v-slot="{ row: { level } }">
            <span v-if="level === 0">
              <el-tag type="success">一级分类</el-tag>
            </span>
            <span v-else-if="level === 1">
              <el-tag type="warning">二级分类</el-tag>
            </span>
            <span v-else-if="level === 2">
              <el-tag type="danger">三级分类</el-tag>
            </span>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-link
              type="primary"
              :underline="false"
              style="margin-right: 10px"
              @click="onEdit(row)"
              ><i class="el-icosn-edit"></i>编辑</el-link
            >
            <el-link type="danger" :underline="false" @click="onDelete(row)"
              ><i class="el-icon-delete"></i>删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import CategoryEdit from "./CategoryEdit";
import * as types from "../../../store/types";
import { treeFind } from "../../../utils/tree";

const nodeMap = new Map();

export default {
  name: "CategoryView",
  components: { CategoryEdit },
  computed: {
    ...mapGetters(["treeCategory", "filterTreeCategory"]),
  },
  data() {
    return {
      // 传递给编辑组件CategoryEdit中的数据
      editCate: {
        id: undefined,
        name: "",
        sort_order: 0,
        parent: undefined,
        banner_image_alt: "",
        image: undefined,
      },
      dialogVisible: false, // 用来控制编辑对话框的显示和隐藏
      isEdit: false, // 用来标记当前做得是更新还是新建的行为
    };
  },
  methods: {
    ...mapActions([
      types.ADD_CATEGORY,
      types.EDIT_CATEGORY,
      types.DELETE_CATEGORY,
    ]),
    load(tree, treeNode, resolve) {
      console.log(this.$refs.table.store.states);

      nodeMap.set(tree.id, { tree, treeNode, resolve });
      console.log(...nodeMap.entries());
      setTimeout(() => {
        resolve(tree.children || []);
      }, 200);
    },
    reload(id) {
      if (!id) return;

      console.log(id);
      console.log(...nodeMap.entries());
      const { resolve } = nodeMap.get(Number(id));
      this.$set(this.$refs.table.store.states.lazyTreeNodeMap, id, []);
      const parentNode = treeFind(this.treeCategory, (node) => node.id === id);

      resolve(parentNode.children ? parentNode.children : []);
    },
    // 编辑提交的方法
    async onSubmit(data) {
      // 如果是编辑状态就调用更新数据的接口
      if (this.isEdit) {
        const result = await this[types.EDIT_CATEGORY](data);

        this.reload(result.parent);

        this.$message.success("更新成功！");
      } else {
        // 如果是新建状态， 就调用新建数据的接口
        const result = await this[types.ADD_CATEGORY](data);
        this.reload(result.parent);
      }
      this.dialogVisible = false;
      this.clearEdit();
      this.isEdit = false;
    },
    // 清空编辑的数据
    clearEdit() {
      this.isEdit = false;
      this.editCate = {
        id: undefined,
        name: "",
        sort_order: 0,
        parent: undefined,
        banner_image_alt: "",
      };
    },
    // 用于做商品分类数据更新的方法
    onEdit(data) {
      //注意！ 不要直接把data 赋值给 this.editCate  直接赋值传递的就是引用，子组件中会直接修改到我们的最终数据
      // 要传递一个原数据的 浅拷贝， 避免组件中修改数据影响到我们的最终数据
      this.editCate = { ...this.editCate, ...data };
      this.dialogVisible = true;
      this.isEdit = true;
    },

    onDelete(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "危险", {
        confirmButtonText: "确定",
        cancelButtonText: "三思而行",
        type: "warning",
      })
        .then(async () => {
          const result = await this[types.DELETE_CATEGORY](data);
          this.reload(result.parent);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    beforeClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.clearEdit();
          done();
        })
        .catch((_) => {
          this.$message({
            type: "info",
            message: "已取消关闭",
          });
        });
    },
  },
};
</script>

<style scoped></style>
